package com.shujia.flink.core

import org.apache.flink.contrib.streaming.state.RocksDBStateBackend
import org.apache.flink.runtime.state.filesystem.FsStateBackend
import org.apache.flink.streaming.api.environment.CheckpointConfig
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup

object Demo6Checkpoint {
  def main(args: Array[String]): Unit = {


    /**
      *
      * 创建flink环境
      * StreamExecutionEnvironment  流处理所需要的环境
      *
      *
      */

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment


    /**
      * 开启checkpoint
      *
      */

    // 每 1000ms 开始一次 checkpoint// 每 1000ms 开始一次 checkpoint
    env.enableCheckpointing(1000)

    // 高级选项：

    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    // 开启在 job 中止后仍然保留的 externalized checkpoints
    env.getCheckpointConfig.enableExternalizedCheckpoints(ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)

    // 允许在有更近 savepoint 时回退到 checkpoint
    env.getCheckpointConfig.setPreferCheckpointForRecovery(true)


    //设置状态后端
    env.setStateBackend(new RocksDBStateBackend("hdfs://master:9000/flink/checkpoints"))


    //读取socket数据
    // nc -lk 9999
    val linesDS: DataStream[String] = env.socketTextStream("master", 9999)

    //实时统计单词数量   累加统计
    val countDS: DataStream[(String, Int)] = linesDS
      .flatMap(_.split(","))
      .map(word => (word, 1))
      .keyBy(kv => kv._1)
      .sum(1)


    //内部调用sink
    countDS.print()


    //启动flink程序
    env.execute()

    /**
      *
      * flink run  -c com.shujia.flink.core.Demo6Checkpoint -s hdfs://master:9000/flink/checkpoints/7c16e075ec49
      * 63ab184e7c13211d0bfc/chk-286  -p 2 flink-1.0.jar
      *
      */


  }

}
